package com.zhj.agent.matcher;

import com.zhj.agent.core.AbstractJunction;
import com.zhj.agent.core.ProtectiveShieldMatcher;
import com.zhj.agent.support.ClassEnhancePluginDefine;

import net.bytebuddy.description.type.TypeDescription;
import net.bytebuddy.matcher.ElementMatcher;

import java.util.LinkedList;
import java.util.Map;

import static net.bytebuddy.matcher.ElementMatchers.isInterface;
import static net.bytebuddy.matcher.ElementMatchers.nameStartsWithIgnoreCase;
import static net.bytebuddy.matcher.ElementMatchers.not;

/**
 * 名称匹配器
 */
public class NamedMatcher implements TypeMatcher<Map<String, LinkedList<ClassEnhancePluginDefine>>> {

    /**
     * Load
     *
     * @param <T>              parameter
     * @param enhancePluginMap enhance plugin map
     * @return the element matcher
     * @since 0.0.1
     */
    @Override
    public <T extends TypeDescription> ElementMatcher<T> load(Map<String, LinkedList<ClassEnhancePluginDefine>> enhancePluginMap) {
        ElementMatcher.Junction<TypeDescription> elementMatcher = new AbstractJunction<TypeDescription>() {
            @Override
            public boolean matches(TypeDescription typeDescription) {
                return enhancePluginMap.containsKey(typeDescription.getActualName());
            }
        };
        //不能是接口的类型
        elementMatcher = elementMatcher.and(not(isInterface()));
        for (String matchClass : enhancePluginMap.keySet()) {
            elementMatcher = elementMatcher.or(nameStartsWithIgnoreCase(matchClass));
        }
        return new ProtectiveShieldMatcher<>(elementMatcher);
    }
}
